//
//  BKGDSpecificationController.m
//  bestkeep
//
//  Created by 毛韶谦 on 2017/1/11.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BKGDSpecificationController.h"

#define BKGDSpecificationViewPlaceholderImage [UIImage imageNamed:@"BKGDDefault"]

const NSInteger kBKGDMaxCellSpacingValue = 10;

@interface BKGDSpecificationCollectionLayout : UICollectionViewFlowLayout

@end

@implementation BKGDSpecificationCollectionLayout

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    
    NSArray* attributesToReturn = [super layoutAttributesForElementsInRect:rect];
    for (UICollectionViewLayoutAttributes* attributes in attributesToReturn) {
        
        if (nil == attributes.representedElementKind) {
            NSIndexPath* indexPath = attributes.indexPath;
            attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
        }
    }
    return attributesToReturn;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewLayoutAttributes* currentItemAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
    
    UIEdgeInsets sectionInset = self.sectionInset;
    
    if (indexPath.item == 0) {
        
        CGRect frame = currentItemAttributes.frame;
        frame.origin.x = self.sectionInset.left;
        currentItemAttributes.frame = frame;
        
        return currentItemAttributes;
    }
    
    NSIndexPath* previousIndexPath = [NSIndexPath indexPathForItem:indexPath.item-1 inSection:indexPath.section];
    CGRect previousFrame = [self layoutAttributesForItemAtIndexPath:previousIndexPath].frame;
    CGFloat previousFrameRightPoint = previousFrame.origin.x + previousFrame.size.width + kBKGDMaxCellSpacingValue;
    
    CGRect currentFrame = currentItemAttributes.frame;
    CGRect strecthedCurrentFrame = CGRectMake(0,
                                              currentFrame.origin.y,
                                              self.collectionView.frame.size.width,
                                              currentFrame.size.height);
    
    if (!CGRectIntersectsRect(previousFrame, strecthedCurrentFrame)) {
        
        CGRect frame = currentItemAttributes.frame;
        frame.origin.x = sectionInset.left;
        currentItemAttributes.frame = frame;
        return currentItemAttributes;
    }
    
    CGRect frame = currentItemAttributes.frame;
    frame.origin.x = previousFrameRightPoint;
    currentItemAttributes.frame = frame;
    return currentItemAttributes;
}

@end

@interface BKGDSpecificationHeaderView : UICollectionReusableView

@property(nonatomic,strong) UILabel *titleLabel;

@end

@implementation BKGDSpecificationHeaderView

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [self initialize];
    }
    return self;
}

-(void)initialize {
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.font = [UIFont systemFontOfSize:13];
    _titleLabel.textColor = RGBACOLOR(64, 64, 64, 64);
    _titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [self addSubview:_titleLabel];
}

-(void)layoutSubviews {
    [super layoutSubviews];
    _titleLabel.frame = self.bounds;
}

-(void)fillData:(BKGDPropertyObject*)obj {
    _titleLabel.text = obj.name;
}

@end


typedef NS_ENUM(NSInteger, BKGDSegmentType) {
    BKGDSegmentTypeMinus = 0,
    BKGDSegmentTypePlus = 2
};

@protocol BKGDSpecificationSegmentedFooterDelegate <NSObject>

@optional
-(void)specificationSegmentedValueChanged:(NSInteger)value;

@end

@interface BKGDSpecificationSegmentedFooterView : UICollectionReusableView

@property(nonatomic,strong,readonly) UISegmentedControl *segmentedControl;
@property(nonatomic,assign,readonly) NSInteger number;
@property(nonatomic,strong,readonly) UILabel *titleLabel;
@property(nonatomic,strong,readonly) UILabel *messageLabel;
@property(nonatomic,assign) BOOL isHidenSegmented;
@property (nonatomic, assign) NSInteger stockValue;
@property (nonatomic, assign) NSInteger canBuyAmount;

@property(nonatomic,weak) id<BKGDSpecificationSegmentedFooterDelegate> delegate;



@end

@implementation BKGDSpecificationSegmentedFooterView

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [self initialize];
    }
    return self;
}

-(void)initialize {
    
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.font = [UIFont systemFontOfSize:15];
    _titleLabel.textColor = RGBACOLOR(64, 64, 64, 1);
    _titleLabel.text = BKGDLocalizedString(@"BKGDSpecificationSegmented");
    [self addSubview:_titleLabel];
    
    _segmentedControl = [[UISegmentedControl alloc] init];
    _segmentedControl.backgroundColor = [UIColor whiteColor];
    _segmentedControl.momentary = YES;
    _segmentedControl.tintColor = [UIColor clearColor];
    _segmentedControl.layer.borderWidth = 0.5;
    _segmentedControl.layer.borderColor = RGBACOLOR(64, 64, 64, 1).CGColor;
    
    [_segmentedControl setDividerImage:[self createImageWithColor:RGBACOLOR(64, 64, 64, 1)] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    [_segmentedControl insertSegmentWithImage:[[UIImage imageNamed:@"BKGDMinus"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] atIndex:0 animated:NO];
    [_segmentedControl insertSegmentWithTitle:[NSString stringWithFormat:@"%ld", (long)_number] atIndex:1 animated:NO];
    [_segmentedControl insertSegmentWithImage:[[UIImage imageNamed:@"BKGDPlus"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] atIndex:2 animated:NO];
    [_segmentedControl addTarget:self action:@selector(segmentedValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self addSubview:_segmentedControl];
    
    [self computeNumberWithType:BKGDSegmentTypePlus];
    
//    [_segmentedControl setEnabled:NO forSegmentAtIndex:1];
    [_segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} forState:UIControlStateNormal];
    
    _messageLabel = [[UILabel alloc] init];
    _messageLabel.font = UIFontSmall;
    _messageLabel.textColor = RGBACOLOR(178, 178, 178, 1);
    _messageLabel.numberOfLines = 2;
    _messageLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [self addSubview:_messageLabel];
}

-(UIImage*)createImageWithColor:(UIColor*)color{
    CGRect rect = CGRectMake(0.0f, 0.0f, 0.5f, 24.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}


-(void)layoutSubviews {
    [super layoutSubviews];
    if(_isHidenSegmented) {
        _messageLabel.frame = CGRectMake(0, 20, CGRectGetWidth(self.frame) - 10, 30);
    } else {
        _titleLabel.frame = CGRectMake(0, 20, 100, 24);
        _segmentedControl.frame = CGRectMake(CGRectGetWidth(self.frame) - 5 - 80, CGRectGetMinY(_titleLabel.frame), 80, CGRectGetHeight(_titleLabel.frame));
        _messageLabel.frame = CGRectMake(0, CGRectGetMaxY(_titleLabel.frame) + 10, CGRectGetWidth(self.frame) - 10, CGRectGetHeight(self.frame) - CGRectGetMaxY(_titleLabel.frame) - 10);
    }
}

-(void)segmentedValueChanged:(UISegmentedControl*)segmentControl {
    NSInteger selectedIndex = segmentControl.selectedSegmentIndex;
    if(selectedIndex == 1) {
        return;
    }
    [self computeNumberWithType:selectedIndex];
    if(_delegate && [_delegate respondsToSelector:@selector(specificationSegmentedValueChanged:)]) {
        [_delegate specificationSegmentedValueChanged:_number];
    }
}

-(void)computeNumberWithType:(BKGDSegmentType)type {
    switch (type) {
        case BKGDSegmentTypeMinus: {//减
            [self minus:1];
        }
            break;
        case BKGDSegmentTypePlus: {//加
            [self plus:1];
        }
    }
    
    NSString *title = [NSString stringWithFormat:@"%ld", (long)_number];
    [_segmentedControl setTitle:title forSegmentAtIndex:1];
    BOOL allowMinus = _number > 1;
    [_segmentedControl setEnabled:allowMinus forSegmentAtIndex:0];
}

-(void)minus:(NSInteger)count {
    NSInteger n = _number - count;
    _number = n < 1 ? 1 : n;
}

-(void)plus:(NSInteger)count {
    
    if (_stockValue > _canBuyAmount) {
        if (_number == _canBuyAmount && _number != 0) {
            [HUD showErrorMessage:[NSString stringWithFormat:@"最多只能买%ld件", _canBuyAmount]];
            return;
        }
    }else{
        if (_number == _stockValue && _number != 0) {
            [HUD showErrorMessage:[NSString stringWithFormat:@"最多只能买%ld件", _stockValue]];
            return;
        }
    }
    
//    if (_number == _stockValue && _number != 0) {
//        [HUD showErrorMessage:[NSString stringWithFormat:@"最多只能买%ld件", _stockValue]];
//        return;
//    }
    _number = _number + count;
}

-(void)setIsHidenSegmented:(BOOL)isHidenSegmented {
    _isHidenSegmented = isHidenSegmented;
    _titleLabel.hidden = _isHidenSegmented;
    _segmentedControl.hidden = _isHidenSegmented;
    
    [self setNeedsLayout];
}

-(void)fillFooterData:(BKGDObject*)goodsDetail {
    if(!goodsDetail) {
        return;
    }
    BOOL isHideSegment = goodsDetail.saleType == 0 || goodsDetail.saleType == 3;
    BOOL isShowLimit = goodsDetail.goodscollect.quotaFlag;
    BOOL isShowSendDate = goodsDetail.saleType == 4 && goodsDetail.sendDate;
    
    NSMutableString *muString = [NSMutableString string];
    if(isShowSendDate) {
        [muString appendFormat:@"%@%@\n", BKGDLocalizedString(@"BKGDSpecificationSendDate"), goodsDetail.sendDate];
    }
    if(isShowLimit) {
        [muString appendFormat:@"%@", goodsDetail.goodscollect.quotaMessage];
    }
    
//    self.messageLabel.text = muString;
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:muString];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5;
    [attString addAttributes:@{NSParagraphStyleAttributeName: style} range:(NSRange){0, attString.string.length}];
    self.messageLabel.attributedText = attString;
    
    
    self.isHidenSegmented = isHideSegment;
    
    _messageLabel.hidden = !isShowLimit && !isShowSendDate;
    
    BKGDCollectObject *goodsCollect = goodsDetail.goodscollect;
    _canBuyAmount = goodsCollect.canBuyAmount;
    
    BKGDSKUObject *sku = goodsDetail.skuList.firstObject;
    _stockValue = sku.stock;
}

+(CGFloat)computeHeight:(BKGDObject*)goodsDetail {
    if(!goodsDetail) {
        return 0;
    }
    BOOL isHideSegment = goodsDetail.saleType == 0 || goodsDetail.saleType == 3;
    BOOL isShowLimit = goodsDetail.goodscollect.quotaFlag;
    BOOL isShowSendDate = goodsDetail.saleType == 4 && goodsDetail.sendDate;
    CGFloat height = 20;
    if(!isHideSegment) {
        height += 24;
        height += 10;
    }
    if(isShowLimit) {
        height += 15;
    }
    if(isShowSendDate) {
        height += 15;
    }
    height += 5;
    
    return height;
}

@end

@interface SectionModel(BKGDSpecification)
@property(nonatomic,strong) NSString *BKGD_footerIdentifier;
@property(nonatomic,assign) CGFloat BKGD_footerHeight;

@end

@implementation SectionModel(BKGDSpecification)

static char const BKGD_footerIdentifierKey = '\0';

-(void)setBKGD_footerIdentifier:(NSString *)BKGD_footerIdentifier {
    objc_setAssociatedObject(self, &BKGD_footerIdentifierKey, BKGD_footerIdentifier, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSString *)BKGD_footerIdentifier {
    return objc_getAssociatedObject(self, &BKGD_footerIdentifierKey);
}

static char const BKGD_footerHeightKey = '\0';

-(void)setBKGD_footerHeight:(CGFloat)BKGD_footerHeight {
    objc_setAssociatedObject(self, &BKGD_footerHeightKey, @(BKGD_footerHeight), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(CGFloat)BKGD_footerHeight {
    NSNumber *value = objc_getAssociatedObject(self, &BKGD_footerHeightKey);
    if(value) {
        return [value floatValue];
    }
    return 0.0f;
}

@end



@interface BKGDSpecificationItemCell : UICollectionViewCell

@property(nonatomic,strong) UILabel *titleLabel;
@property(nonatomic,strong) CAShapeLayer *unavailableLayer;
@property(nonatomic,strong) CAShapeLayer *dashLayer;

@end

@implementation BKGDSpecificationItemCell

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [self initialize];
    }
    return self;
}

-(void)initialize {
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.font = UIFontSmall;
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    _titleLabel.layer.masksToBounds = YES;
    _titleLabel.layer.cornerRadius = 2;
    [self.contentView addSubview:_titleLabel];
    
    _unavailableLayer = [[CAShapeLayer alloc] init];
    _unavailableLayer.lineWidth = 1;
    _unavailableLayer.lineCap = kCALineCapRound;
    _unavailableLayer.strokeColor = RGBACOLOR(178, 178, 178, 1).CGColor;
    _unavailableLayer.hidden = YES;
//    [self.contentView.layer addSublayer:_unavailableLayer];
    
    _dashLayer = [[CAShapeLayer alloc] init];
    _dashLayer.strokeColor = RGBACOLOR(178, 178, 178, 1).CGColor;
    _dashLayer.frame = self.bounds;
    _dashLayer.lineWidth = 1;
    _dashLayer.lineCap = kCALineCapRound;
    _dashLayer.lineDashPattern = @[@4, @2];
    _dashLayer.fillColor = [UIColor clearColor].CGColor;
    _dashLayer.hidden = YES;
    [_titleLabel.layer addSublayer:_dashLayer];
}

-(void)layoutSubviews {
    [super layoutSubviews];
    _titleLabel.frame = self.bounds;
}

-(UIBezierPath*)unavailablePath {
    CGRect frame = self.frame;
    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:CGPointMake(1, CGRectGetHeight(frame) - 1)];
    [path addLineToPoint:CGPointMake(CGRectGetWidth(frame) - 1, 1)];
    return path;
}

/**
 未选中样式
 */
-(void)deSelectStyle {
    _titleLabel.layer.borderWidth = 1;
    _titleLabel.textColor = RGBACOLOR(162, 162, 162, 1);
    _titleLabel.layer.borderColor = RGBACOLOR(178, 178, 178, 1).CGColor;
    _unavailableLayer.hidden = YES;
    _dashLayer.hidden = YES;
    
}

/**
 选中样式
 */
-(void)selectedStyle {
    _titleLabel.layer.borderWidth = 1;
    _titleLabel.textColor = RGBACOLOR(0, 186, 156, 1);
    _titleLabel.layer.borderColor = _titleLabel.textColor.CGColor;
    _unavailableLayer.hidden = YES;
    _dashLayer.hidden = YES;
    [_unavailableLayer removeFromSuperlayer];
}

/**
 不可选中样式
 */
-(void)disabledStyle {
    [self.contentView.layer addSublayer:_unavailableLayer];
    _unavailableLayer.hidden = NO;
    _titleLabel.textColor = RGBACOLOR(162, 162, 162, 1);
    _titleLabel.layer.borderWidth = 1;
    _titleLabel.layer.borderColor = RGBACOLOR(178, 178, 178, 1).CGColor;
    _unavailableLayer.path = [self unavailablePath].CGPath;
    _dashLayer.hidden = YES;
}

/**
 虚线样式
 */
-(void)dashStyle {
    
    _titleLabel.layer.borderWidth = 0;
    _titleLabel.textColor = RGBACOLOR(162, 162, 162, 1);
    _dashLayer.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
    _unavailableLayer.hidden = YES;
    _dashLayer.hidden = NO;
    [_unavailableLayer removeFromSuperlayer];
}

+(CGSize)computeSize:(NSString*)text {
    if(!text) {
        return CGSizeMake(0, 0);
    }
    CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName: UIFontCustom(14)}];
//    textSize.width += 15;
    textSize.width += 30;
    if(textSize.width < 50) {
        textSize.width = 50;
    }
    
//    textSize.height += 10;
    textSize.height = 35;
    
    return textSize;
}

-(void)fillData:(BKGDPropertyItemObject*)obj {
    if(!obj) {
        return;
    }
    self.titleLabel.text = obj.propertyValue;
    //可以选择
    if(obj.available) {
        //已经被选中
        if(obj.isSelected) {
            [self selectedStyle];
        } else {
            //表示与当前被选中项不匹配（虚线）
            if(obj.isMismatching) {
                [self dashStyle];
            } else {
                [self deSelectStyle];
            }
        }
        
    } else {
        [self disabledStyle];
    }
    
}

@end





NSString *const BKGDSpecificationCellIdentifier = @"BKGDSpecificationCellIdentifier";
NSString *const BKGDSpecificationHeaderIdentifier = @"BKGDSpecificationHeaderIdentifier";
NSString *const BKGDSpecificationSegmentedFooterIdentifier = @"BKGDSpecificationSegmentedFooterIdentifier";
NSString *const BKGDSpecificationViewFooterNormalIdentifier = @"BKGDSpecificationViewFooterNormalIdentifier";

@interface BKGDSpecificationController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong) UIView *topLineView;
@property(nonatomic,strong) UIImageView *imageView;
@property(nonatomic,strong) UILabel *titleLabel;
@property(nonatomic,strong) UIView *lineView;
@property(nonatomic,strong) UIImageView *closeImageView;
@property(nonatomic,strong) UIButton *bottomButton;

@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong) NSArray<SectionModel*> *dataArray;
@property(nonatomic,strong) NSDictionary<NSString*, NSIndexPath*> *dataMapping;
@property(nonatomic,strong) NSIndexPath *currentSelectedIndexPath;

@end

@implementation BKGDSpecificationController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeComponent];
}

-(void)initializeComponent {
    
    _selectedCount = 1;
    self.view.backgroundColor = [UIColor whiteColor];
    _topLineView = [[UIView alloc] init];
    _topLineView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.00];
    [self.view addSubview:_topLineView];
    
    _imageView = [[UIImageView alloc] init];
    _imageView.backgroundColor = [UIColor whiteColor];
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    _imageView.layer.cornerRadius = 0.5;
    _imageView.layer.masksToBounds = YES;
    _imageView.layer.borderColor = _topLineView.backgroundColor.CGColor;
    _imageView.layer.borderWidth = 1 / [[UIScreen mainScreen] scale];
    [self.view addSubview:_imageView];
    
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    _titleLabel.numberOfLines = 3;// 0;

//    _titleLabel.backgroundColor = [UIColor redColor];
    [self.view addSubview:_titleLabel];
    
    _lineView = [[UIView alloc] init];
    _lineView.backgroundColor = _topLineView.backgroundColor;
    [self.view addSubview:_lineView];
    
    _closeImageView = [[UIImageView alloc] init];
    _closeImageView.image = [UIImage imageNamed:@"BKGDSpecificationClose"];
    _closeImageView.contentMode = UIViewContentModeCenter;
    _closeImageView.userInteractionEnabled = YES;
    [self.view addSubview:_closeImageView];
    
    UITapGestureRecognizer *closeImageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeImageViewTap:)];
    closeImageTap.numberOfTapsRequired = 1;
    [_closeImageView addGestureRecognizer:closeImageTap];
    
    BKGDSpecificationCollectionLayout *layout = [[BKGDSpecificationCollectionLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumLineSpacing = 13;
    layout.minimumInteritemSpacing = 16;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.alwaysBounceVertical = YES;
    [_collectionView registerClass:[BKGDSpecificationHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:BKGDSpecificationHeaderIdentifier];
    [_collectionView registerClass:[BKGDSpecificationSegmentedFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:BKGDSpecificationSegmentedFooterIdentifier];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:BKGDSpecificationViewFooterNormalIdentifier];
    [_collectionView registerClass:[BKGDSpecificationItemCell class] forCellWithReuseIdentifier:BKGDSpecificationCellIdentifier];
    [self.view addSubview:_collectionView];
    
    _bottomButton = [[UIButton alloc] init];
    [_bottomButton setBackgroundImage:[Common imageWithFrame:CGRectMake(0, 0, 1, 1) color:[UIColor redColor]] forState:UIControlStateNormal];
    [_bottomButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_bottomButton addTarget:self action:@selector(bottomBottunTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bottomButton];
    
    [self makeConstraints];
}

-(void)makeConstraints {
    [_topLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(1 / [[UIScreen mainScreen] scale]);
    }];
    
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(-20);
        make.left.mas_equalTo(12);
        make.size.mas_equalTo(CGSizeMake(100, 100));
    }];
    
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(10);
        make.left.equalTo(_imageView.mas_right).offset(10);
        make.right.mas_equalTo(0);
        make.bottom.equalTo(_imageView.mas_bottom);
    }];
    
    [_closeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    [_lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_imageView.mas_bottom).offset(10);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(1 / [[UIScreen mainScreen] scale]);
    }];
    
    [_bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(49);
    }];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_lineView.mas_bottom).offset(1);
        make.left.equalTo(self.view.mas_left).offset(12);
        make.right.equalTo(self.view.mas_right).offset(-12);
        make.bottom.equalTo(_bottomButton.mas_top);
    }];
}

#pragma -mark 绑定数据
-(void)setGoodsDetail:(BKGDObject *)goodsDetail {
    if(!goodsDetail || _goodsDetail == goodsDetail) {
        return;
    }
    
    _goodsDetail = goodsDetail;
    
    [self refreshTitleLabelFromSelectedItems:nil];
    
    [self refreshBottomButtonStyle:_goodsDetail.btnText isBuy:_goodsDetail.isBuy];
    
    if(_goodsDetail.goodsImages) {
        [_imageView load:_goodsDetail.goodsImages[0] placeholderImage:BKGDSpecificationViewPlaceholderImage];
    }
    
    [self loadCollectionViewData:goodsDetail];
}

-(void)loadCollectionViewData:(BKGDObject*)goodsDetail {
    NSArray<BKGDPropertyObject*> *propertyListArray = goodsDetail.propertyListArray;
    
    if(propertyListArray && propertyListArray.count > 0) {
        
        NSMutableArray<SectionModel*> *sections = [NSMutableArray array];
        
        NSMutableDictionary<NSString*, NSIndexPath*> *mappingDictionary = [NSMutableDictionary dictionary];
        
        for (int i = 0; i< propertyListArray.count; i++) {
            BKGDPropertyObject *obj = propertyListArray[i];
            
            NSMutableArray<CellModel*> *cells = [NSMutableArray array];
            
            NSArray<BKGDPropertyItemObject*> *proItemList = obj.propertyRelList;
            for (int j = 0; j < proItemList.count; j++) {
                BKGDPropertyItemObject *item = proItemList[j];
                CellModel *itemCell = [[CellModel alloc] init];
                itemCell.title = item.propertyValue;
                itemCell.className = NSStringFromClass([BKGDSpecificationItemCell class]);
                itemCell.userInfo = item;
                itemCell.size = [BKGDSpecificationItemCell computeSize:item.propertyValue];
                itemCell.selectorString = NSStringFromSelector(@selector(cellDidSelectedAtIndexPath:));
                itemCell.reuseIdentifier = BKGDSpecificationCellIdentifier;
                [cells addObject:itemCell];
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
                [mappingDictionary setObject:indexPath forKey:item.id];
            }
            
            SectionModel *s = [[SectionModel alloc] init];
            s.userInfo = obj;
            s.headerhHeight = 40;
            s.className = NSStringFromClass([BKGDSpecificationHeaderView class]);
            s.reuseIdentifier = BKGDSpecificationHeaderIdentifier;
            s.cells = cells;
            
            [sections addObject:s];
        }
        
        SectionModel *lastSection = sections.lastObject;
        lastSection.BKGD_footerIdentifier = BKGDSpecificationSegmentedFooterIdentifier;
        lastSection.BKGD_footerHeight = [BKGDSpecificationSegmentedFooterView computeHeight:_goodsDetail];
        
        _dataArray = sections;
        _dataMapping = mappingDictionary;
        [self sortedSKUProperties:_goodsDetail];
        [_collectionView reloadData];
    } else {//没有sku选择，但可以选择购买数量
        if(_goodsDetail.saleType != 0 && _goodsDetail.saleType != 3) {
            NSMutableArray<SectionModel*> *sections = [NSMutableArray array];
            
            SectionModel *s = [[SectionModel alloc] init];
            s.userInfo = nil;
            s.headerhHeight = 0;
            s.className = NSStringFromClass([BKGDSpecificationHeaderView class]);
            s.reuseIdentifier = BKGDSpecificationHeaderIdentifier;
//            s.cells = cells;
            s.BKGD_footerHeight = [BKGDSpecificationSegmentedFooterView computeHeight:_goodsDetail];
            s.BKGD_footerIdentifier = BKGDSpecificationSegmentedFooterIdentifier;
            [sections addObject:s];
            
            _dataArray = sections;
            [_collectionView reloadData];
        }
    }
}

/**
 对sku属性项根据显示顺序进行排序
 */
-(void)sortedSKUProperties:(BKGDObject*)goodsDetail {
    if(!goodsDetail.skuList || goodsDetail.skuList.count == 0) {
        return;
    }
    for (BKGDSKUObject *skuItem in _goodsDetail.skuList) {
        
        NSArray *skuProIds = [skuItem.skuProIds componentsSeparatedByString:@","];
        NSArray *sortedSKUProIds = [skuProIds sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            
            NSIndexPath *ip1 = _dataMapping[obj1];
            NSIndexPath *ip2 = _dataMapping[obj2];
            if(ip1.section < ip2.section) {
                return NSOrderedAscending;
            }
            return NSOrderedDescending;
        }];
        
        NSString *skuDataItemId = [sortedSKUProIds componentsJoinedByString:@""];
        skuItem.sortedProIds = skuDataItemId;
    }
}

-(void)refreshBottomButtonStyle:(NSString*)title isBuy:(NSInteger)type {
    if(_goodsDetail.goodscollect.canBuyAmount <= 0) {
        type = 0;
    }
    
    UIColor *color = type == 0 ? BKGDDisabledColor : type == 1 ? BKGDMainColor : BKGDYellowColor;
    
    BOOL enabled;
    switch (type) {
        case 0: { //不可用
            color = BKGDDisabledColor;
            enabled = NO;
            title = BKGDLocalizedString(@"BKGDSpecificationButtonDefaultTitle");
        }
            break;
        case 1: { //可买
            color = BKGDMainColor;
            enabled = YES;
            title = BKGDLocalizedString(@"BKGDSpecificationButtonDefaultTitle");
        }
            break;
        default: { //到货通知
            color = BKGDYellowColor;
            enabled = YES;
        }
            break;
    }
    
    [_bottomButton setTitle:title forState:UIControlStateNormal];
    [_bottomButton setEnabled:enabled];
    [_bottomButton setBackgroundImage:[Common imageWithFrame:CGRectMake(0, 0, 1, 1) color:color] forState:UIControlStateNormal];
}

#pragma -mark 点叉关闭按钮
-(void)closeImageViewTap:(UIGestureRecognizer*)recognizer {
    if(_delegate && [_delegate respondsToSelector:@selector(specificationDidTouchClose:)]) {
        [_delegate specificationDidTouchClose:self];
    }
}

#pragma -mark bottomButtou Touch

-(void)bottomBottunTouchUpInside:(UIButton*)sender {
    
    if(_goodsDetail.propNumber == 0) {
        _selectedObject = _goodsDetail.skuList[0];
    }
    
    if(!self.selectedObject) {
        
        [self showUserSelectError];
        
        return;
    }
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(specification:bottomButtonTouchUpInside:)]) {
        [self.delegate specification:self bottomButtonTouchUpInside:sender];
    }
}

-(void)showUserSelectError {
    NSMutableString *message = [NSMutableString stringWithString:BKGDLocalizedString(@"BKGDSpecificationNoSelected")];
    for (SectionModel *s in _dataArray) {
        BOOL isSelected = NO;
        for (CellModel *row in s.cells) {
            BKGDPropertyItemObject *item = row.userInfo;
            if(item.isSelected) {
                isSelected = YES;
                break;
            }
        }
        if(!isSelected) {
            BKGDPropertyObject *obj = s.userInfo;
            [message appendFormat:@"%@ ", obj.name];
        }
    }
    
    [HUD showErrorMessage:message];
}

#pragma -mark collectionView delegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _dataArray.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SectionModel *s = _dataArray[section];
    return s.cells.count;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    SectionModel *s = _dataArray[section];
    CGSize size = CGSizeMake(CGRectGetWidth(collectionView.frame), s.headerhHeight);
    return size;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    SectionModel *s = _dataArray[section];
    CGSize size = CGSizeMake(CGRectGetWidth(collectionView.frame), s.BKGD_footerHeight);
    return size;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    SectionModel *s = _dataArray[indexPath.section];
    
    UICollectionReusableView *reusableView;
    
    if([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:s.reuseIdentifier forIndexPath:indexPath];
        SEL selector = NSSelectorFromString(@"fillData:");
        if([reusableView respondsToSelector:selector]) {
            ((void (*)(void *, SEL, id))objc_msgSend)((__bridge void *)(reusableView), selector, s.userInfo);
        }
    } else {
        NSString *identifier = s.BKGD_footerIdentifier ? s.BKGD_footerIdentifier : BKGDSpecificationViewFooterNormalIdentifier;
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:identifier forIndexPath:indexPath];
        if([reusableView isKindOfClass:[BKGDSpecificationSegmentedFooterView class]]) {
            [reusableView setValue:self forKey:@"delegate"];
        }
        SEL selector = NSSelectorFromString(@"fillFooterData:");
        if([reusableView respondsToSelector:selector]) {
            ((void (*)(void *, SEL, id))objc_msgSend)((__bridge void *)(reusableView), selector, _goodsDetail);
        }
    }
    
    return reusableView;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *s = _dataArray[indexPath.section];
    CellModel *row = s.cells[indexPath.row];
    return row.size;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *s = _dataArray[indexPath.section];
    CellModel *row = s.cells[indexPath.row];
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:row.reuseIdentifier forIndexPath:indexPath];
    
//    if(SystemVersion < 8.0) {
//        [self configCell:cell atIndexPath:indexPath];
//    }
    [self configCell:cell atIndexPath:indexPath];

    return cell;
}

//-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
//    [self configCell:cell atIndexPath:indexPath];
//}

-(void)configCell:(UICollectionViewCell*)cell atIndexPath:(NSIndexPath*)indexPath {
    SectionModel *s = _dataArray[indexPath.section];
    CellModel *row = s.cells[indexPath.row];
    SEL selector = NSSelectorFromString(@"fillData:");
    if([cell respondsToSelector:selector]) {
        ((void (*)(void *, SEL, id))objc_msgSend)((__bridge void *)(cell), selector, row.userInfo);
    }
}

-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *s = _dataArray[indexPath.section];
    CellModel *row = s.cells[indexPath.row];
    
    BKGDPropertyItemObject *itemObj = row.userInfo;
    if(itemObj.available && !itemObj.isSelected) {
        return YES;
    }
    return NO;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:NO];
    
    SectionModel *s = _dataArray[indexPath.section];
    CellModel *row = s.cells[indexPath.row];
    
    SEL selector = NSSelectorFromString(row.selectorString);
    if([self respondsToSelector:selector]) {
        ((void (*)(void *, SEL, id))objc_msgSend)((__bridge void *)(self), selector, indexPath);
    }
}

#pragma -mark segment delegate

-(void)specificationSegmentedValueChanged:(NSInteger)value {
    _selectedCount = value;
    if(_delegate && [_delegate respondsToSelector:@selector(specification:selectedCountChanged:)]) {
        [_delegate specification:self selectedCountChanged:_selectedCount];
    }
}

#pragma -mark cell点击
-(void)cellDidSelectedAtIndexPath:(NSIndexPath*)indexPath {
    _currentSelectedIndexPath = indexPath;
    
    SectionModel *s = _dataArray[indexPath.section];
    CellModel *row = s.cells[indexPath.row];
    
    //上次选中的项目（同一个section）
    BKGDPropertyItemObject *lastSelectedItem = [self getSelectedItemWithSection:indexPath.section];
    if(lastSelectedItem) {
        lastSelectedItem.isSelected = NO;
    }
    
    BKGDPropertyItemObject *currentSelectedItem = row.userInfo;
    if(currentSelectedItem.isMismatching == YES) {
        [self resetSelectedItems];
    }
    currentSelectedItem.isSelected = YES;
    
    if(currentSelectedItem.img && ![currentSelectedItem.img isEqualToString:@""]) {
        [_imageView load:currentSelectedItem.img placeholderImage:BKGDSpecificationViewPlaceholderImage];
    }
    
    [self analyzeMatching];
    
    NSArray<BKGDPropertyItemObject*> *selectedItems = [self getSelectedItems];
    
    if(selectedItems && selectedItems.count > 0) {
        
        NSMutableString *itemIdsString = [NSMutableString string];
        for (BKGDPropertyItemObject *item in selectedItems) {
            [itemIdsString appendString:item.id];
        }
        
        BKGDSKUObject *selectedSKUObject;
        for (BKGDSKUObject *skuObj in _goodsDetail.skuList) {
            if([skuObj.sortedProIds isEqualToString:itemIdsString]) {
                selectedSKUObject = skuObj;
                NSLog(@"已经匹配到商品：%@", skuObj);
                break;
            }
        }
        
        if(selectedSKUObject) {
            
            _selectedObject = selectedSKUObject;
            [self refreshBottomButtonStyle:selectedSKUObject.btnText isBuy:selectedSKUObject.isBuy];
            NSString *text = [self textFromSelectedItems:selectedItems];
            _selectedMessage = text;
            
            if(self.delegate && [self.delegate respondsToSelector:@selector(specification:DidSelectedSKUObject:selectMessage:)]) {
                [self.delegate specification:self DidSelectedSKUObject:selectedSKUObject selectMessage:text];
            }
            
        } else {
            _selectedObject = nil;
        }
        
        [self refreshTitleLabelFromSelectedItems:selectedItems];
    }
    
//    [_collectionView reloadData];
    
    [UIView performWithoutAnimation:^{
        [_collectionView reloadData];
    }];
    
}

/**
 分析是否有不匹配的项（虚线）
 */
-(void)analyzeMatching {
    
    NSMutableArray<BKGDPropertyItemObject*> *selectedItems = [self getSelectedItems];
    
    //逐级判断
    for (int i = 0; i < _dataArray.count; i++) {
        NSArray<CellModel*> *cells = _dataArray[i].cells;
        
        NSMutableArray<BKGDPropertyItemObject*> *tempArray = [NSMutableArray arrayWithArray:selectedItems];
        
        //使用选中的项进行匹配分析
        for (BKGDPropertyItemObject *item in selectedItems) {
            NSIndexPath *indexPath = _dataMapping[item.id];
            //如果为当前组
            if(indexPath.section == i) {
                //选项为多个时
                if(cells.count > 1) {
                    //在选中的项中移除当前项
                    [tempArray removeObject:item];
                }
            }
        }
        
        //对子项进行判断
        for (CellModel *row in cells) {
            BKGDPropertyItemObject *item = row.userInfo;
            if(item.available == 0) {
                continue;
            }
            //将当前子项加入到已经选择的项中
            [tempArray addObject:item];
            //判断当前项与选中的项 是否有不匹配的商品 （只要有一次匹配说明此项可以在接下来被选择，否则为虚线显示）
            item.isMismatching = [self isMismatchingWithItems:tempArray];
            
            [tempArray removeObject:item];
        }
        
    }
}

-(BOOL)isMismatchingWithItems:(NSArray<BKGDPropertyItemObject*>*)items {
    
    NSMutableString *itemIdsString = [NSMutableString string];
    for (BKGDPropertyItemObject *item in items) {
        [itemIdsString appendString:item.id];
    }
    
    NSArray<BKGDSKUObject*> *skuObjects = [_goodsDetail skuList];
    
    BOOL isMismatching = NO;
    
    for (BKGDSKUObject *skuObj in skuObjects) {
        NSArray<NSString*> *skuProIds = [skuObj.skuProIds componentsSeparatedByString:@","];
        NSInteger containsLength = 0;
        for (NSString *proId in skuProIds) {
            containsLength += [itemIdsString rangeOfString:proId].length;
        }
        
        if(containsLength == itemIdsString.length) {
            if(skuObj.isBuy == 0) {
                isMismatching = YES;
            } else {
                isMismatching = NO;
                break;
            }
        }
    }
    
    return isMismatching;
}

//重置选中状态
-(void)resetSelectedItems {
    for (SectionModel *s in _dataArray) {
        
        for (CellModel *row in s.cells) {
            BKGDPropertyItemObject *item = row.userInfo;
            item.isSelected = NO;
            item.isMismatching = NO;
        }
    }
}

-(BKGDPropertyItemObject*)getSelectedItemWithSection:(NSInteger)section {
    //每个section只能有一个项被选中
    SectionModel *s = _dataArray[section];
    NSArray<CellModel*> *cells = s.cells;
    for (CellModel *row in cells) {
        BKGDPropertyItemObject *item = row.userInfo;
        if(item.isSelected) {
            return item;
        }
    }
    return nil;
}

-(NSMutableArray<BKGDPropertyItemObject*>*)getSelectedItems {
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < _dataArray.count; i++) {
        BKGDPropertyItemObject *item = [self getSelectedItemWithSection:i];
        if(item) {
            [array addObject:item];
        }
    }
    return array;
}

#pragma -mark 刷新标题
-(void)refreshTitleLabelFromSelectedItems:(NSArray<BKGDPropertyItemObject*>*)array {
    
    NSString *price;
    NSString *stock;
    NSString *selectText = array ? [self textFromSelectedItems:array] : nil;
    
    BOOL isVIP = _goodsDetail.userLevel.vipFlag;
    
    BKGDSKUObject *skuObj = _goodsDetail.propNumber == 0 ? _goodsDetail.skuList[0] : _selectedObject;
    
    if(skuObj) {
        price = isVIP ? skuObj.price1 : skuObj.price2;
        
        if(skuObj.stock > 0 && _goodsDetail.saleType != 0 && _goodsDetail.saleType != 3) {
            stock = [NSString stringWithFormat:@"%@%ld", BKGDLocalizedString(@"BKGDSpecificationSurplus"), (long)skuObj.stock];
        }
    } else {
        price = isVIP ? _goodsDetail.price1 : _goodsDetail.price2;
    }
    
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
    [attString appendAttributedString:[[NSAttributedString alloc] initWithString:price attributes:@{NSFontAttributeName: UIFontCustom(20), NSForegroundColorAttributeName: RGBACOLOR(255, 16, 16, 1)}]];
    
    if(stock) {
        stock = [NSString stringWithFormat:@"\n%@ %@", stock, BKGDLocalizedString(@"BKGDSpecificationUnits")];
        [attString appendAttributedString:[[NSAttributedString alloc] initWithString:stock attributes:@{NSFontAttributeName: UIFontCustom(13), NSForegroundColorAttributeName: RGBACOLOR(64, 64, 64, 1)}]];
    }
    if(selectText) {
        selectText = [NSString stringWithFormat:@"\n%@", selectText];
        [attString appendAttributedString:[[NSAttributedString alloc] initWithString:selectText attributes:@{NSFontAttributeName: UIFontCustom(13), NSForegroundColorAttributeName: RGBACOLOR(64, 64, 64, 1)}]];
    }
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5;
    if (stock) {
        style.lineBreakMode = NSLineBreakByTruncatingTail;
    }else{
        style.lineBreakMode = NSLineBreakByCharWrapping;
    } 
    [attString addAttributes:@{NSParagraphStyleAttributeName: style} range:(NSRange){0, attString.string.length}];
    
    _titleLabel.attributedText = attString;

}

-(NSString*)textFromSelectedItems:(NSArray<BKGDPropertyItemObject*>*)array {
    
    NSMutableString *str = [NSMutableString stringWithString:BKGDLocalizedString(@"BKGDSpecificationSelected")];
    for (BKGDPropertyItemObject *item in array) {
        [str appendFormat:@"\"%@\" ", item.propertyValue];
    }
    
    return [NSString stringWithString:str];
}

@end
